package com.jagochan.imchat.module.wx.service.impl;

import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.core.util.StrUtil;
import com.jagochan.imchat.module.user.adaptor.UserAdaptor;
import com.jagochan.imchat.module.user.dao.UserDao;
import com.jagochan.imchat.module.user.domain.entity.User;
import com.jagochan.imchat.module.user.service.UserService;
import com.jagochan.imchat.module.websocket.service.WebSocketService;
import com.jagochan.imchat.module.wx.adaptor.TextBuilder;
import com.jagochan.imchat.module.wx.service.WxMsgService;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class WxMsgServiceImpl implements WxMsgService {
    /**
     * 缓存openId和code(场景值)
     */
    private static final ConcurrentHashMap<String, Integer> OPENID_CODE_MAP = new ConcurrentHashMap<>();

    private static final String QR_SCENE_ = "qrscene_";

    private static final String AUTHORIZE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

    @Value("${wx.mp.redirectUri}")
    private String redirectUri;

    @Resource
    private WebSocketService webSocketService;

    @Resource
    private UserDao userDao;

    @Resource
    private UserService userService;

    @Override
    public WxMpXmlOutMessage scan(WxMpXmlMessage wxMpXmlMessage, WxMpService wxMpService) {
        String openId = wxMpXmlMessage.getFromUser();
        Integer code = getEventKeyCode(wxMpXmlMessage.getEventKey());
        if (Objects.isNull(code)) {
            return null;
        }

        User user = userDao.getByOpenId(openId);
        Boolean registered = Objects.nonNull(user); // 已注册
        Boolean authorized = registered && StrUtil.isNotBlank(user.getAvatar()); // 已授权
        if (registered && authorized) { // 用户已经注册了，并且也授权了
            webSocketService.scanLoginSuccess(code, user.getId());
            return null;
        }
        if (!registered) { // 进行注册操作
            user = UserAdaptor.buildRegister(openId);
            userService.register(user);
        }

        // 缓存openId和code的映射关系（将来要根据openId拿到code,然后根据code拿到Channel）
        OPENID_CODE_MAP.put(openId, code);
        // 向客户端发送消息（如 扫码成功等待授权）
        webSocketService.waitAuthorize(code);

        // 构造重定向地址（用户点击后请求的地址）
        String authorizeUrl = String.format(AUTHORIZE_URL, wxMpService.getWxMpConfigStorage().getAppId(), URLEncodeUtil.encode(redirectUri + "/wx/portal/public/callBack"));
        return TextBuilder.build("点击【登陆】👉 <a href=\"" + authorizeUrl + "\">登录</a>", wxMpXmlMessage);
    }

    /**
     * 微信授权（填充用户信息）
     *
     * @param userInfo
     */
    @Override
    public void authorize(WxOAuth2UserInfo userInfo) {
        User user = userDao.getByOpenId(userInfo.getOpenid());
        if (user == null) return;

        if (StrUtil.isBlank(user.getAvatar())) {
            fillUserInfo(user.getId(), userInfo);
        }
        Integer code = OPENID_CODE_MAP.remove(user.getOpenId());
        webSocketService.scanLoginSuccess(code, user.getId());
    }

    private void fillUserInfo(Long uid, WxOAuth2UserInfo userInfo) {
        User user = UserAdaptor.buildAuthorize(uid, userInfo);
        userDao.updateById(user);
    }

    /**
     * eventKey也可称作code
     */
    private Integer getEventKeyCode(String eventKey) {
        if (Objects.isNull(eventKey)) return null;
        if (eventKey.contains(QR_SCENE_)) {
            eventKey = eventKey.replace(QR_SCENE_, "");
        }
        return new Integer(eventKey);
    }
}
